package com.mobilesales.android.c2dm.parsers;

import android.content.Context;
import android.util.Log;

import com.mobilesales.android.database.ProductManager;
import com.mobilesales.android.model.products.Category;
import com.mobilesales.android.model.products.Product;
import com.mobilesales.android.model.products.Tax;
import com.mobilesales.android.model.products.Unit;
import com.mobilesales.android.services.ProductServiceClient;
import com.mobilesales.android.util.Settings;

public class ProductMessageParser extends MessageParserBase {

	private ProductManager manager;
	private ProductServiceClient service;

	public ProductMessageParser(Context context) {
		super(context);
	}
	
	public ProductMessageParser() {
		super();
	}	
	
	@Override
	public boolean parseMessage(String method, String arg) {
		manager = new ProductManager(getContext());
		service = new ProductServiceClient(Settings.ProductService());
		try {
			this.invokeMethod(ProductMessageParser.class, method,arg);
			return true;
		}
		catch(Exception ex) {
			Log.e("MessageParser", ex.getMessage(), ex);
			return false;
		}
		finally {
			manager.Close();
		}
	}
	
	public void GetCategory(Integer id) throws Exception {
		Category item = service.getCategory(id);
		if (item!=null) {
			if (!manager.StoreCategory(item))
				throw new Exception("Could not store category");
		}
		else {
			throw new Exception("Retrieved category is null");
		}		
	}
	
	public void DeleteCategory(Integer id) throws Exception {

		if (!manager.RemoveCategory(id))
			throw new Exception("Could not delete category");
	}	
	
	public void GetTax(Integer id) throws Exception {
		Tax item = service.GetTax(id);
		if (item!=null) {
			if (!manager.StoreTax(item))
				throw new Exception("Could not store tax");
		}
		else {
			throw new Exception("Retrieved tax is null");
		}
	}
	
	public void DeleteTax(Integer id) throws Exception {
		if (!manager.RemoveTax(id))
			throw new Exception("Could not delete tax");
	}	
	
	public void GetUnit(Integer id) throws Exception {
		Unit item = service.GetUnit(id);
		if (item!=null) {
			if (!manager.StoreUnit(item))
				throw new Exception("Could not store unit");
		}
		else {
			throw new Exception("Retrieved unit is null");
		}
	}
	
	public void DeleteUnit(Integer id) throws Exception {
		if (!manager.RemoveUnit(id))
			throw new Exception("Could not delete unit");
	}		
	
	public void GetProduct(Integer id) throws Exception {
		Product item = service.getProduct(id);
		if (item!=null) {
			if (!manager.StoreProduct(item))
				throw new Exception("Could not store product");
		}
		else {
			throw new Exception("Retrieved product is null");
		}
	}
	
	public void DeleteProduct(Integer id) throws Exception {
		if (!manager.RemoveProduct(id))
			throw new Exception("Could not delete product");

	}
}
